package com.buba.config;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {

    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager")DefaultWebSecurityManager defaultWebSecurityManager){
        ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
        //设置安全管理器
        bean.setSecurityManager(defaultWebSecurityManager);
        /**
         * 添加shiro的内置过滤器
         *         anno无需认证就可访问
         *         authc必需认证才可访问
         *         user必需拥有记住我功能才能用
         *         perms拥有对某个资源的权限才能访问
         *         role 拥有某个角色权限才能访问
         */
        //拦截
        Map<String, String> filterMap = new LinkedHashMap<>();

        //授权,正常的情况下未授权会跳转到未授权页面
        filterMap.put("/user/add","perms[user:add]");
        filterMap.put("/user/upd","perms[user:upd]");


        //设置过滤拦截
        filterMap.put("/user/*","authc");
        bean.setFilterChainDefinitionMap(filterMap);


        //设置登录的请求
        bean.setLoginUrl("/toLogin");

        //设置未授权
        bean.setUnauthorizedUrl("/unAuthorized");
        return bean;

    }

    //defaultWebSecurityManager 2..
    @Bean(name = "securityManager")//spring默认使用方法名为name
    public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userReaml") UserReaml userReaml){
        DefaultWebSecurityManager securityManager =  new DefaultWebSecurityManager();
        //UserReaml
        securityManager.setRealm(userReaml);
        return  securityManager;
    }

    //创建realm对象，需要自定义 1..
    @Bean//spring默认使用方法名为name
    public UserReaml userReaml(){
        return new UserReaml();
    }

    //整合shiroDialect:用来整合shiro thymeleaf
    @Bean//spring默认使用方法名为name
    public ShiroDialect getShiroDialect(){
        return new ShiroDialect();
    }
}
